<template>
  <div 
    class="node"
    :class="{ 'selected': isSelected }"
    :style="nodeStyle"
    @mousedown="handleMouseDown"
  >
    <!-- 节点标题 -->
    <div class="node-header">
      <h4 class="node-title">{{ node.title }}</h4>
      <div class="node-type">{{ node.type }}</div>
    </div>
    
    <!-- 节点字段列表 -->
    <div class="node-fields">
      <div 
        v-for="field in node.fields"
        :key="field.name"
        class="field-item"
        :class="{ 'primary-key': field.isPrimaryKey }"
      >
        <i 
          v-if="field.isPrimaryKey" 
          class="el-icon-key field-icon"
        ></i>
        <i 
          v-else-if="field.isRequired" 
          class="el-icon-star-on field-icon required"
        ></i>
        <i 
          v-else 
          class="el-icon-minus field-icon"
        ></i>
        <span class="field-name">{{ field.name }}</span>
        <span class="field-type">{{ field.type }}</span>
      </div>
    </div>
    
    <!-- 连接点 -->
    <div class="connection-points">
      <div 
        v-for="point in connectionPoints"
        :key="point"
        :class="`connection-point connection-point-${point}`"
        @mousedown="handleConnectionStart(point, $event)"
      ></div>
    </div>
  </div>
</template>

<script>
import { mapState,mapActions } from 'vuex'
import {isPointNearConnectionPoint} from '@/util'
import { v4 as uuidv4 } from 'uuid'
export default {
  name: 'Node',
  props: {
    node: {
      type: Object,
      required: true
    },
    scale: {
      type: Number,
      default: 1
    },
    panX: {
      type: Number,
      default: 0
    },
    panY: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      connectionPoints: ['top', 'right', 'bottom', 'left'],
      // 拖拽相关状态
      isDragging: false,
      dragStartX: 0,
      dragStartY: 0,
      nodeStartX: 0,
      nodeStartY: 0,
      //连接点拖拽相关状态
      isConnectionPointDragging: false,
      connectionPointStartX: 0,
      connectionPointStartY: 0,
      point:''
    }
  },
  computed: {
    ...mapState(['selectedNodeIds','targetPoints','targetXY']),
    
    isSelected() {
      return this.selectedNodeIds.includes(this.node.id)
    },

    nodeStyle() {
    return {
      position: 'absolute',
      left: `${this.node.x}px`,
      top: `${this.node.y}px`,
      width: `${this.node.style.width}px`,
      height: `${this.node.style.height}px`,
      backgroundColor: this.node.style.backgroundColor,
      borderColor: this.node.style.borderColor,
      zIndex: this.isSelected ? 1000 : 1,
      cursor: this.isDragging ? 'grabbing' : 'grab',
      opacity: this.isDragging ? 0.8 : 1
    }
  }


  },
  methods: {
    ...mapActions(['updateNewConnectionPath','addConnection']),

    // 处理连接点开始连接
    handleConnectionStart(point, event) {
    event.stopPropagation()
    event.preventDefault()
    this.point = point
    // TODO: 实现连接线创建逻辑
    this.$emit('createConnection', this.node.id, point)
    this.isConnectionPointDragging = true
    //记录连接点开始位置
    this.connectionPointStartX = event.clientX
    this.connectionPointStartY = event.clientY
    console.log(`连接点创建连接`,this.connectionPointStartX,this.connectionPointStartY,event)
    document.addEventListener('mousemove', this.handleConnectionMove)
    document.addEventListener('mouseup', this.handleConnectionEnd)
    },
    
    //处理连接点移动
    handleConnectionMove(event) {
      if(!this.isConnectionPointDragging) return
      // TODO: 实现连接线移动逻辑
      //计算连接点移动距离
      const dx = event.clientX - this.connectionPointStartX
      const dy = event.clientY - this.connectionPointStartY
      //更新连接路径
      // this.$emit('connectionTargetNode',{
      //   x: dx,
      //   y: dy
      // })
      this.updateNewConnectionPath({
        x: dx,
        y: dy
      })

    },
    
    //处理连接点结束
    handleConnectionEnd(event) {
      // TODO: 实现连接线结束逻辑
      const newTarget = isPointNearConnectionPoint(this.targetXY, this.targetPoints)
      if (!newTarget.targetPoint) {
        this.isConnectionPointDragging = false
        document.removeEventListener('mousemove', this.handleConnectionMove)
        document.removeEventListener('mouseup', this.handleConnectionEnd)
        this.updateNewConnectionPath(null)
        return
      }
      if (newTarget.targetPoint.targetNode.id === this.node.id)  return
      const newConnection = {
        id:uuidv4(),
        sourceNodeId: this.node.id,
        targetNodeId: newTarget ? newTarget.targetPoint.targetNode.id : null,
        sourcePoint: this.point,
        targetPoint: newTarget ? newTarget.targetPoint.point : null,
        style: {
        strokeColor: this.node.style.borderColor,
        strokeWidth: 2
       }
      }
      console.log(newConnection,newTarget.targetPoint,'连接点结束');
      this.addConnection(newConnection)//添加链接线
      //结束拖拽状态并重置连接点位置
      this.isConnectionPointDragging = false
      this.updateNewConnectionPath(null)
      document.removeEventListener('mousemove', this.handleConnectionMove)
      document.removeEventListener('mouseup', this.handleConnectionEnd)
    },

    // 处理鼠标按下开始拖拽
    handleMouseDown(event) {
    // 如果点击的是连接点，不处理拖拽
    if (event.target.classList.contains('connection-point')) {
      return
    }
    
    event.preventDefault()// 阻止默认行为
    event.stopPropagation()// 阻止事件冒泡
    
    this.isDragging = true
    this.dragStartX = event.clientX// 记录鼠标按下时的位置
    this.dragStartY = event.clientY
    this.nodeStartX = this.node.x// 记录节点开始位置
    this.nodeStartY = this.node.y
    
    // 添加全局鼠标事件监听
    document.addEventListener('mousemove', this.handleMouseMove)
    document.addEventListener('mouseup', this.handleMouseUp)
    
    // 选中当前节点
    this.$emit('node-select', this.node.id, event)
    },
    
    // 处理鼠标移动拖拽
    handleMouseMove(event) {
      if (!this.isDragging) return
      
      event.preventDefault()// 阻止默认行为
      
      const deltaX = event.clientX - this.dragStartX// 计算鼠标移动的距离
      const deltaY = event.clientY - this.dragStartY
      
      const newX = this.nodeStartX + deltaX / this.scale// 计算节点新的位置
      const newY = this.nodeStartY + deltaY / this.scale
      
      // 更新节点位置到store
      this.$store.commit('UPDATE_NODE_POSITION', {
        nodeId: this.node.id,
        x: newX,
        y: newY
      })
    },
    
    // 处理鼠标释放结束拖拽
    handleMouseUp(event) {
      if (!this.isDragging) return
      
      this.isDragging = false
      
      // 移除全局鼠标事件监听
      document.removeEventListener('mousemove', this.handleMouseMove)
      document.removeEventListener('mouseup', this.handleMouseUp)
    }
  
  },
  // 组件销毁时清理事件监听
  beforeDestroy() {
    document.removeEventListener('mousemove', this.handleMouseMove)
    document.removeEventListener('mouseup', this.handleMouseUp)
  }
}
</script>

<style scoped>
.node {
  border: 2px solid;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  user-select: none;
  transition: box-shadow 0.2s, opacity 0.2s;
  overflow: hidden;
}

.node:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.node.selected {
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.3);
}

.node-header {
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.node-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.node-type {
  font-size: 12px;
  color: #666;
  background: rgba(0, 0, 0, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

.node-fields {
  padding: 8px 0;
  max-height: 200px;
  overflow-y: auto;
}

.field-item {
  display: flex;
  align-items: center;
  padding: 4px 12px;
  font-size: 12px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.field-item:last-child {
  border-bottom: none;
}

.field-item.primary-key {
  background: rgba(255, 193, 7, 0.1);
}

.field-icon {
  width: 16px;
  margin-right: 6px;
  color: #666;
}

.field-icon.required {
  color: #f56c6c;
}

.field-name {
  flex: 1;
  font-weight: 500;
  color: #333;
}

.field-type {
  color: #666;
  font-family: monospace;
}

.connection-points {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.connection-point {
  position: absolute;
  width: 10px;
  height: 10px;
  background: #409eff;
  border: 2px solid white;
  border-radius: 50%;
  cursor: crosshair;
  pointer-events: auto;
  opacity: 0;
  transition: all 0.2s;
}

.node:hover .connection-point {
  transform: scale(1.5);
  opacity: 1;
}

.connection-point-top {
  top: -6px;
  left: 50%;
  transform: translateX(-50%);
}

.connection-point-right {
  right: -6px;
  top: 50%;
  transform: translateY(-50%);
}

.connection-point-bottom {
  bottom: -6px;
  left: 50%;
  transform: translateX(-50%);
}

.connection-point-left {
  left: -6px;
  top: 50%;
  transform: translateY(-50%);
}
</style>